package com.lagou.handler;

import com.lagou.pojo.RpcRequest;
import com.lagou.util.LongToBytes;
import com.lagou.util.SpringContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {
    private CuratorFramework client;

    public UserServiceHandler(CuratorFramework client) {
        this.client = client;
    }

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //注意:  客户端将来发送请求的时候会传递一个RpcRequest对象，强转处理
        RpcRequest rpcRequest = (RpcRequest) msg;
        //获取容器中的bean
        String className = rpcRequest.getClassName().substring(rpcRequest.getClassName().lastIndexOf(".") + 1);
        Object object = SpringContextUtil.getBean(className);
        //获取客户端调用的方法
        Method method = object.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        //调用实现类获得一个result
        Object result = method.invoke(object, rpcRequest.getParameters());
        //把调用实现类的方法获得的结果写到客户端
        ctx.writeAndFlush(result);
        //向zookeeper删除并重新创建节点
        client.delete().deletingChildrenIfNeeded().forPath("/netty/40001/time");
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/netty/40001/time");
    }
}
